<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title" style="height: 65px">
        <div style="margin-bottom: 5px; margin-top: 5px">
          <!-- <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" />
          </a-space>
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp; -->
          <space style="float: right; margin-right: 10px; margin-top: 15px">
            <a-button type="primary" @click="handleExport"> 导出统计表</a-button>
          </space>&nbsp;&nbsp;&nbsp;&nbsp;
        </div>
      </div>
      <a-table style="margin-top: 0px" :dataSource="tableData" :columns="displayColumns" :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }" bordered :loading="loading" />
      <div class="pagination" style="float: right">
        <a-pagination show-size-changer v-model:current="pageIndex" v-model:pageSize="pageSize" :total="total"
          @show-size-change="onShowSizeChange" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import moment from 'moment';
import dayjs from 'dayjs';
import { ref, reactive, toRefs, onMounted, onBeforeMount, computed, watch } from 'vue';
import { getgdjsbplist } from '/@/api/demo/hoursebase'; //统计
import { useUserStore } from '/@/store/modules/user';
import { useRouter } from 'vue-router';
import { iTableData, iTableColumns } from './types/table';
import { iParams } from './types/params';
import { useGlobSetting } from '/@/hooks/setting';
import { downloadByUrl } from '/@/utils/file/download';
import { useCheckStore } from '/@/store/modules/checkStore';
const userStore = useUserStore();
const router = useRouter();
const globSetting = useGlobSetting();
let userInfo = ref<any>(null);
let detailTableHeight = ref<number>(0); // 表格高度
let tableHeight = ref<number>(0); // 表格高度
let pageIndex = ref(1);
let pageSize = ref(15);
const dateFormat = 'YYYY-MM-DD';
const startDate = ref<any>(null); // 开始时间
const endDate = ref<any>(null); // 结束时间
let total = ref(0);
const store = useCheckStore();
let data = reactive<{
  tableData: iTableData[];
  tableColumns: iTableColumns[];
  wscolsList: { wch: number }[];
  id: number | any;
  loading: Boolean;
  keyWorld: String;
  currentqx: string; // 当前行政区名称
  currentTitle: string;
  cityToken: string | any;
  startTime: string;
  endTime: string;
}>({
  // 表格数据
  tableData: [],
  tableColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 80,
    },
    {
      title: '区名称',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 80,
    },
    {
      title: '房屋总数',
      dataIndex: 'zcount',
      key: 'zcount',
      align: 'center',
      width: 100,
    },
    {
      title: '安装固定警示标牌栋数',
      dataIndex: 'xggdjsbpds',
      key: 'xggdjsbpds',
      align: 'center',
      width: 200,
    },
    {
      title: '未安装固定警示标牌栋数',
      dataIndex: 'no_xggdjsbpds',
      key: 'no_xggdjsbpds',
      align: 'center',
      width: 200,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row);
          },
        };
      },
    },
    {
      title: '安装率',
      dataIndex: 'azl_pencent',
      key: 'azl_pencent',
      align: 'center',
      width: 200,
    },
    {
      title: '出租房间数',
      dataIndex: 'jzfjs',
      key: 'jzfjs',
      align: 'center',
      width: 200,
    },
    {
      title: '安装固定警示标牌个数',
      dataIndex: 'xggdjsbpcount',
      key: 'xggdjsbpcount',
      align: 'center',
      width: 200,
    },
    {
      title: '房间安装率',
      dataIndex: 'fjzal_pencent',
      key: 'fjzal_pencent',
      align: 'center',
      width: 100,
    },
  ],
  id: null,
  loading: true,
  keyWorld: '',
  cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
  currentqx: '', // 当前行政区名称
  currentTitle: '', // 当前详情标题
  wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
  endTime: '',
  startTime: '',
});
// 表格的 ref Dom名称
let { tableData, loading, currentqx, currentTitle } = toRefs(data);
async function getData() {
  if (startDate.value == null) {
    let currentDate = moment().format('YYYY-MM-DD');
    const start: any = dayjs('2024-01-01');
    const end: any = dayjs(currentDate);
    startDate.value = start;
    endDate.value = end;
    getTime();
  }
  let params: iParams = {
    pageIndex: pageIndex.value,
    pageSize: pageSize.value,
    startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
    endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
  };
  loading.value = true;
  let res: any = await getgdjsbplist(params);
  console.log('@res--工作进入汇总表', res.items);

  if (res || res.items.length > 0) {
    loading.value = false;
    // console.log('data', data);
    // 算列和
    let zcount = vtotal(res.items, 'zcount');
    let xggdjsbpds = vtotal(res.items, 'xggdjsbpds');
    let no_xggdjsbpds = vtotal(res.items, 'no_xggdjsbpds');
    let azl_pencent;
    // 将变量转为数字类型，并检查有效性
    const numxggdjsbpds = parseFloat(xggdjsbpds);
    const numzcount = parseFloat(zcount);

    // 验证：确保两个值都是有效数字，且分母不为0
    if (!isNaN(numxggdjsbpds) && !isNaN(numzcount) && numzcount !== 0) {
      const ratio = (numxggdjsbpds / numzcount) * 100;
      azl_pencent = ratio.toFixed(2) + '%'; // 直接保留两位小数（无需Math.round）
    } else {
      // 处理无效情况（按需自定义回退值）
      azl_pencent = '0%'; // 或 'N/A'、'--'
    }
    let index_count = res.items.length + 1;
    let jzfjs = vtotal(res.items, 'jzfjs');
    let xggdjsbpcount = vtotal(res.items, 'xggdjsbpcount');
    let fjzal_pencent;
    // 将变量转为数字类型，并检查有效性
    const numxggdjsbpcount = parseFloat(xggdjsbpcount);
    const numjzfjs = parseFloat(jzfjs);

    // 验证：确保两个值都是有效数字，且分母不为0
    if (!isNaN(numxggdjsbpcount) && !isNaN(numjzfjs) && numjzfjs !== 0) {
      const ratio = (numxggdjsbpcount / numjzfjs) * 100;
      fjzal_pencent = ratio.toFixed(2) + '%'; // 直接保留两位小数（无需Math.round）
    } else {
      // 处理无效情况（按需自定义回退值）
      fjzal_pencent = '0%'; // 或 'N/A'、'--'
    }


    let allObj = {
      xzq: '汇总',
      zcount: zcount,
      xggdjsbpds: xggdjsbpds,
      no_xggdjsbpds: no_xggdjsbpds,
      index: index_count,
      jzfjs: jzfjs,
      xggdjsbpcount: xggdjsbpcount,
      azl_pencent: azl_pencent,
      fjzal_pencent: fjzal_pencent,
    };
    loading.value = false;
    data.tableData = [...res.items, allObj];
    total.value = res.total;
  }
}
// 计算总数的方法
function vtotal(arr: any, item: any) {
  let total = arr.reduce((pre: any, cur: any) => {
    return parseInt(pre) + parseInt(cur[item]);
  }, 0);
  return total;
}
function getUserInfo() {
  const userStore = useUserStore();
  userInfo.value = userStore?.getUserInfo;
}
//未安装固定警示标牌
const getDetailData = async (row: any) => {
  router.push({
    path: 'xggdjsbp/noposted',
    query: {
      xzq: row.xzq,
      xzqdm: row.xzqdm,
      towndm: '',
      villagedm: '',
      floor: '',
      xggdjsbp: '否',
      currentTitle: row.xzq + '-' + '【未安装固定警示标牌】明细',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    },
  });
};
function searchBtn() {
  data.loading = true;
  getData();
}
function getTime() {
  data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
  data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
  console.log('@查询参数 -- 开始时间', data.startTime);
  console.log('@查询参数 -- 结束时间', data.endTime);
}
const displayColumns = computed(() => {
  const { role } = userInfo.value;
  let arr: any[] = [];
  if (role === 'City') {
    // qx
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
    return arr;
  } else if (role === 'Area') {
    // jz
    arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
    return arr;
  } else if (role === 'Street') {
    // cun
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
    console.log('@Aarr', arr);
    return arr;
  } else {
    return data.tableColumns;
  }
});
function handleExport() {

  const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
  const tk = userStore.getToken;
  downloadByUrl({
    url: uriBase + '/static/xgjsbp/xgjsbpExportExcel?access_token=' + tk + '&txtKeyWord=' + eval,
    target: '_blank',
  });
}

const getTableHeight = () => {
  setTimeout(() => {
    detailTableHeight.value = window.innerHeight;
    tableHeight.value = window.innerHeight;
  });
};
watch(pageSize, () => {
  console.log('pageSize', pageSize.value);
  getData();
});
watch(pageIndex, () => {
  console.log('current', pageIndex.value);
  getData();
});
onBeforeMount(() => {
  getUserInfo();
});
onMounted(() => {
  console.log('******工作进展统计初始化******');
  getData();
  getTableHeight();
  // getTableData();
});
</script>
<style scoped lang="less"></style>
